import 'package:flutter/material.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/authentication.dart';
import 'package:ichinesereader/models/common/LoginDto.dart';
import 'package:ichinesereader/pages/individual/renewsubscription.dart';
import 'package:ichinesereader/utils/StrUtil.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:get/get.dart';

class LoginCardScanner extends StatefulWidget {
  const LoginCardScanner({Key? key}) : super(key: key);

  @override
  _LoginCardScannerState createState() => _LoginCardScannerState();
}

class _LoginCardScannerState extends State<LoginCardScanner>
    with SingleTickerProviderStateMixin {
  String? barcode;
  String message = '';
  MobileScannerController cameraController = MobileScannerController();
  LoginDto logindto = new LoginDto();

  final LoginController _loginManager = Get.find();

  void _login(String username, String access) async {
    logindto.userName = username.trim();
    logindto.sessionType = 'WEB';
    logindto.accessCode = access.trim();
    await _loginManager.login(logindto, false).then((_authMessage) {
      Log.debug('message after login card scanning');
      if (_authMessage.status == LoginStatusKey.logged_in) {
        switch (_loginManager.userRole.value) {
          case Constants.NanhaiRole_Student:
            {
              Get.offAllNamed('/student/home');
              break;
            }
          case Constants.NanhaiRole_Teacher:
            {
              Get.offAllNamed('/teacher/home');
              break;
            }
          case Constants.NanhaiRole_SchoolAdmin:
            {
              Get.offAllNamed('/schooladmin/home');
              break;
            }
          case Constants.NanhaiRole_Individual:
            {
              Get.offAllNamed('/individual/home');
              break;
            }
          case Constants.NanhaiRole_Parent:
            {
              Get.offAllNamed('/parent/home');
              break;
            }
          default:
            Get.offAllNamed('/error');
            break;
        }
      } else if (_authMessage.status == LoginStatusKey.has_placement) {
        Log.debug('card login and redirect to placement page');
        Get.offAllNamed('/placement', arguments: false);
      } else {
        Log.debug('login failure from badge scanning page');
        message = _authMessage.message.toString();
        showSnackMsg(message);
        // Get.snackbar('Message'.tr, message.tr,
        //     backgroundColor: Get.theme.primaryColorDark,
        //     colorText: Get.theme.primaryColorLight,
        //     snackPosition: SnackPosition.BOTTOM);
        if (message == 'Account Expired/Subscription Cancelled') {
          if (GetPlatform.isAndroid || GetPlatform.isIOS) {
            Get.to(() => InAppWebViewIndividualRenewSubscriptionScreen());
          } else {
            launchInWebViewWithJavaScript(
                '${Constants.BaseURL}icr/student/individualPay?webview=true');
          }
        } else {
          //_loginManager.removeToken();
        }
      }
    });
  }

  @override
  void dispose() {
    cameraController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Badge Login'.tr),
          actions: [
            IconButton(
              color: Colors.white,
              icon: ValueListenableBuilder(
                valueListenable: cameraController.torchState,
                builder: (context, state, child) {
                  switch (state as TorchState) {
                    case TorchState.off:
                      return const Icon(Icons.flash_off, color: Colors.grey);
                    case TorchState.on:
                      return const Icon(Icons.flash_on, color: Colors.yellow);
                  }
                },
              ),
              iconSize: 32.0,
              onPressed: () => cameraController.toggleTorch(),
            ),
            IconButton(
              color: Colors.white,
              icon: ValueListenableBuilder(
                valueListenable: cameraController.cameraFacingState,
                builder: (context, state, child) {
                  switch (state as CameraFacing) {
                    case CameraFacing.front:
                      return const Icon(Icons.camera_front);
                    case CameraFacing.back:
                      return const Icon(Icons.camera_rear);
                  }
                },
              ),
              iconSize: 32.0,
              onPressed: () => cameraController.switchCamera(),
            ),
          ],
        ),
        body: MobileScanner(
            //allowDuplicates: false,
            controller: cameraController,
            onDetect: (barcode) {
              try{
                if (barcode.barcodes.first.rawValue == null) {
                debugPrint('Failed to scan login badge');
              } else {
                final String code = barcode.barcodes.first.rawValue!;
                //debugPrint('Badge found! $code');
                if (code.contains('@')) {
                  final values =
                      StrUtil.splitStringByIndex(code, code.lastIndexOf('@'));
                  String _userName = values[0].toString();
                  String _access = values[1].toString();
                  _login(_userName, _access);
                }
              }
              }catch(excpt)
              {
              }
            }));
  }
}
